package com.mzj.saas.mservice.report.service;


import com.mzj.saas.commons.ApiData;
import com.mzj.saas.commons.ResultBean;
import com.mzj.saas.commons.vo.redis.TokenRedisVo;
import com.mzj.saas.mservice.eligible.entity.DepartmentEnterpriseTagRef;
import com.mzj.saas.mservice.eligible.entity.DepartmentHierarchy;
import com.mzj.saas.mservice.eligible.repository.DepartmentEnterpriseTagRefRepository;
import com.mzj.saas.mservice.eligible.repository.DepartmentHierarchyRepository;
import com.mzj.saas.mservice.report.vo.ReportRepairStatisticsVO;
import com.mzj.saas.redis.RedisService;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 报修报事统计
 */
@Service
public class ReportRepairStatisticsService {
    /**
     * 在控制台打印日志信息
     */
    private static final Logger log = LoggerFactory.getLogger(ReportRepairStatisticsService.class);

    @Autowired
    private JdbcTemplate jdbcTemplate;
    @Autowired
    private RedisService redisService;
    @Autowired
    private DepartmentHierarchyRepository departmentHierarchyRepository;
    @Autowired
    private DepartmentEnterpriseTagRefRepository departmentEnterpriseTagRefRepository;
    /**
     * 列表
     * 根据不同的登录用户标签获取不同的报事报修总数据
     * @param accessToken 验证令牌
     * @param pageNumber 起始数据
     * @param pageSize 页面大小
     * @param vo 页面数据
     * @return
     */
    public ResultBean<ApiData<ReportRepairStatisticsVO>> pages(String accessToken, Integer pageNumber, Integer pageSize, ReportRepairStatisticsVO vo) {
        log.info("ReportRepairStatisticsService  pages   accessToken={}, vo={}", accessToken, vo.toString());

        //获取登录用户信息
        TokenRedisVo tokenRedisVo = redisService.findTokenVo(accessToken);
        if (tokenRedisVo == null) {
            //未登录提示异常 40001 --- accessToken失效
            return ResultBean.failedResultOfToken();
        }

        String SQL = "SELECT s.type,SUM(s.private_number) private_number,SUM(s.public_number) public_number FROM saas_report_repair_statistics s inner join saas_department d on s.house_property_id = d.id  ";

        //判断用户所属机构是否设置层级架构
        Long enterpriseId = tokenRedisVo.getEnterpriseId();
        DepartmentHierarchy hierarchy = departmentHierarchyRepository.findByOrgIdAndStatus(enterpriseId, 1);
        if (hierarchy == null) {
            //用户所属机构未设置层级架构 10001 --- 用户所属机构未设置层级架构
            return ResultBean.failedResultWithMsg("用户所属机构未设置层级架构");
        }
        //根据机构层级关系id查出企业与标签关系数据
        Long id = hierarchy.getId();
        List<DepartmentEnterpriseTagRef> refs = departmentEnterpriseTagRefRepository.findByDepRefId(id);
        //去重后的用户企业标签
        List<Long> enterpriseTagIds = refs.stream().map(DepartmentEnterpriseTagRef::getTagId).distinct().collect(Collectors.toList());//用户企业标签

        //1、政府机构，根据区域标签所对应区域id查
        Long areaTagId = hierarchy.getTagId();//区域标签
        Long areaId = null;
        if (enterpriseTagIds.contains(3L)) {
            areaId = hierarchy.getAreaId();//区域id
        }
        String areaTag = "province_id";
        if (areaTagId == 1) {
            areaTag = "province_id";
        } else if (areaTagId == 2) {
            areaTag = "city_id";
        } else if (areaTagId == 3) {
            areaTag = "district_id";
        } else if (areaTagId == 4) {
            areaTag = "street_id";
        } else if (areaTagId == 5) {
            areaTag = "community_id";
        }

        //2、物业
        Long hierarchyOrgId = null;
        if (enterpriseTagIds.contains(4L)) {
            hierarchyOrgId = hierarchy.getOrgId();
        }

        StringBuilder where = new StringBuilder(" WHERE 1=1 ");
        List<Object> args = new ArrayList<>();

        where.append(" and ( d." + areaTag + " = ? or s.house_property_id = ? ) ");
        args.add(areaId);
        args.add(hierarchyOrgId);

        if (vo != null) {
            //时间段查询
            if (StringUtils.isNotBlank(vo.getStartTime()) && StringUtils.isNotBlank(vo.getEndTime())) {
                String startTime = vo.getStartTime();
                String endTime = vo.getEndTime();
                where.append(" and s.stat_date >= ?");
                where.append(" and s.stat_date <= ?");
                args.add(startTime);
                args.add(endTime);
            }
        }

        where.append(" GROUP BY s.type ");
        List<ReportRepairStatisticsVO> data = jdbcTemplate.query(SQL + where, new BeanPropertyRowMapper<>(ReportRepairStatisticsVO.class), args.toArray());

        ApiData<ReportRepairStatisticsVO> apiData = new ApiData<>();
        apiData.setData(data);

        return ResultBean.successfulResult(apiData);
    }


}
